import baseApi from './baseApi';


// 商户类型定义
export interface Merchant {
  id: number;
  name: string;
  logo?: string;
  address?: string;
  phone?: string;
  status: string;
  createdAt: string;
  updatedAt: string;
}

// 商户列表请求参数
export interface MerchantListParams {
  page?: number;
  pageSize?: number;
  search?: string;
}

// 商户列表响应
export interface MerchantListResponse {
  pagination: {
    total: number;
    page: number;
    pageSize: number;
  };
  list: Merchant[];
}

// 商户ID存储键名
const MERCHANT_ID_KEY = 'currentMerchantId';

/**
 * 获取当前选中的商户ID
 */
export const getMerchantId = (): number | null => {
  const idStr = localStorage.getItem(MERCHANT_ID_KEY);
  return idStr ? parseInt(idStr, 10) : null;
};

/**
 * 设置当前选中的商户ID
 */
export const setMerchantId = (id: number): void => {
  localStorage.setItem(MERCHANT_ID_KEY, id.toString());
};

/**
 * 清除当前选中的商户ID
 */
export const clearMerchantId = (): void => {
  localStorage.removeItem(MERCHANT_ID_KEY);
};

/**
 * 获取商户列表
 */
export const getMerchantList = async (params: MerchantListParams = {}): Promise<{
  code: number;
  message: string;
  data: MerchantListResponse | null;
}> => {
  try {
    const response = await baseApi.get('/admin/merchant/list', { params });
    return response.data;
  } catch {
    return {
      code: -1,
      message: '获取商户列表失败',
      data: null
    };
  }
};

/**
 * 获取商户详情
 */
export const getMerchantDetail = async (merchantId: number): Promise<{
  code: number;
  message: string;
  data: Merchant | null;
}> => {
  try {
    const response = await baseApi.get(`/admin/merchant/${merchantId}`);
    return response.data;
  } catch {
    return {
      code: -1,
      message: '获取商户详情失败',
      data: null
    };
  }
};

const merchantService = {
  getMerchantList,
  getMerchantDetail,
  getMerchantId,
  setMerchantId,
  clearMerchantId
};

export default merchantService; 